import axios from 'axios'
import store from '../store'
import {
  Message
} from 'element-ui'
import {
  getStorage
} from './storage'

const service = axios.create({
  timeout: 5000,
  // baseURL: 'http://zbtest.zytbw.com',
  baseURL: 'http://zbapi.zytbw.com',
  // baseURL: 'http://192.168.5.77:8080',
})

service.interceptors.request.use(config => {
  return config
}, error => {
  Promise.reject(error)
})

const correctStatus = [200, 2003]
service.interceptors.response.use(response => {
  if (response.data.status === 501) {
    store.commit('ToggleLoginOpen', true)
  }
  if (!correctStatus.includes(response.data.status)) {
    return response.data
  }
  if (correctStatus.includes(response.data.status)) {
    return response.data.data || response.data
  }
}, error => {
  // Do something with response error
  Message.error('请求失败，请刷新页面重试')
  return Promise.reject(error)
})

/**
 * get请求
 * @param url {string} 请求地址
 * @param params {object} [params={}] 请求参数
 * @param config {object} [config={}] 请求配置
 * @returns {Promise<AxiosResponse<any>>}
 */
function get(url, params = {}, config = {}) {
  const userInfo = getStorage('user_info') || {}
  const token = userInfo.token
  return service.get(url, {
    params,
    headers: {
      token
    },
    ...config
  })
}

/**
 * post请求
 * @param url {string} 请求地址
 * @param data {object} [data={}] 请求参数
 * @param config {object} [config={}] 请求配置
 * @returns {Promise<AxiosResponse<any>>}
 */
function post(url, data = {}, config = {}) {
  const userInfo = getStorage('user_info') || {}
  const token = userInfo.token
  return service.post(url, data, {
    headers: {
      token
    },
    ...config
  })
}

const http = {
  get,
  post
}

export default http
